package zgame.bean;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import zgame.bussiness.ChatBussiness;

public class ChatRoom {
  
  private String name = "";
  
  private String title = "";
  
  private String passwordMd5 = "";
  
  private Map<String, User> members = new HashMap<String, User>();
  
  private User roomMaster;
  
  private int maxUser = Integer.MAX_VALUE;
  
  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }

  public String getTitle() {
    return title;
  }

  public void setTitle(String title) {
    this.title = title;
  }
  
  public boolean isHasPassword() {
    return "".equals(passwordMd5);
  }

  public String getPasswordMd5() {
    return passwordMd5;
  }

  public void setPasswordMd5(String passwordMd5) {
    this.passwordMd5 = passwordMd5;
  }
  
  public User getMember(String username) {
    return members.get(username);
  }
  
  public List<User> getMembers() {
    return new ArrayList<User>(members.values());
  }
  
  public void addMember(User user) {
    ChatBussiness.notifyUserGetInRoom(this, user);
    
    // Put user to room
    members.put(user.getUsername(), user);
    user.setChatRoom(this);
    
    // If room has only one member, so user is room master
    if (members.size() == 1) {
      roomMaster = user;
    }
  }
  
  public boolean removeMember(User user) {
    if (getMember(user.getUsername()) == null) {
      return false;
    }
    
    // Remove user from room
    members.remove(user.getUsername());
    user.setChatRoom(null);
    ChatBussiness.notifyUserGetOutRoom(this, user);
    
    // Check if user is room master then change this permission to another user
    if (roomMaster.getUsername().equals(user.getUsername())) {
      if (members.size() > 0) {
        roomMaster = members.get(0);
      } else {
        roomMaster = null;
      }
    }
    
    return true;
  }
  
  public User getRoomMaster() {
    return roomMaster;
  }

  public void setRoomMaster(User roomMaster) {
    this.roomMaster = roomMaster;
  }
  
  public int getMaxUser() {
    return maxUser;
  }

  public void setMaxUser(int maxUser) {
    this.maxUser = maxUser;
  }
  
  public int getNumberOfMember() {
    return members.size();
  }

  public void broadcastMessage(String fromUser, String message) {
    ChatBussiness.broadcastMessage(fromUser, message, this);
  }

  @Override
  public String toString() {
    StringBuilder builder = new StringBuilder();
    builder.append("ChatRoom[");
    builder.append(" name=\"" + name + "\", ");
    builder.append(" title=\"" + title + "\", ");
    builder.append(" passwordMd5=\"" + passwordMd5 + "\", ");
    builder.append(" roomMaster=\"" + ((roomMaster == null) ? null : roomMaster.getUsername()) + "\", ");
    builder.append(" maxUser=" + maxUser + "");
    return builder.toString();
  }
}
